<?php

/**
 * ==============================================
 * Created by Finger Technology.
 * Author: ZhiHuaWei <zhihua_wei@foxmail.com>
 * Date: 2019/8/25 12:04
 * Project: YunAdmin
 * Power: YunAdmin 上传类控制器
 * Version: 1.0.0
 * ==============================================
 */

namespace app\admin\controller;

use think\Db;
use think\Exception;
use think\Image;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * 上传类
 * Class Uploads
 * @package app\admin\controller
 */
class Uploads extends YunAdmin
{
    /**
     * 头像图片上传
     * @param $name
     * @param $file_path
     * @return array
     */
    public function uploadHeadImg($name, $file_path)
    {
        # 1 根据表单名称获取上传的图片文件
        try {
            $file = request()->file($name);
            if ($file) {
                # 2 将其保存在uploads文件夹下 | 后续如果想要保存在云端也可在此修改
                $file_paths = UPLOAD_PATH . $file_path;
                if (!file_exists($file_paths)) {
                    mkdir($file_paths, 0777, true);
                }
                $info = $file->move($file_paths);
                if ($info) {
                    # 3 保存原始图片文件
                    $img_path = 'uploads/' . $file_path . '/' . $info->getSaveName();
                    $thumb_image = Image::open($img_path);
                    $date_path = 'uploads/' . $file_path . '/thumb/' . date('Ymd');
                    if (!file_exists($date_path)) {
                        mkdir($date_path, 0777, true);
                    }
                    # 4 保存缩略图
                    $thumb_140_path = $date_path . '/140_' . $info->getFilename();
                    $thumb_30_path = $date_path . '/30_' . $info->getFilename();
                    $thumb_image->thumb(140, 140)->save($thumb_140_path);
                    $thumb_image->thumb(30, 30)->save($thumb_30_path);
                    $data['img'] = config('app_host') . $img_path;
                    $data['thumb_140_img'] = config('app_host') . $thumb_140_path;
                    $data['thumb_30_img'] = config('app_host') . $thumb_30_path;
                    # 5 成功结果返回
                    $ret_data = [
                        'code' => 1,
                        'msg' => 'SUCCESS',
                        'data' => $data
                    ];
                    return $ret_data;
                } else {
                    # 6 失败结果返回
                    $ret_data = [
                        'code' => 0,
                        'msg' => $file->getError(),
                        'data' => []
                    ];
                    return $ret_data;
                }
            }
        } catch (Exception $e) {
            $ret_data = [
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => []
            ];
            return $ret_data;
        }
    }

    /**
     * 文章插图上传
     * @param $name
     * @param $file_path
     * @return array
     */
    public function uploadArticleImg($name, $file_path)
    {
        # 1 根据表单名称获取上传的图片文件
        try {
            $file = request()->file($name);
            if ($file) {
                # 2 将其保存在uploads文件夹下 | 后续如果想要保存在云端也可在此修改
                $file_paths = UPLOAD_PATH . $file_path;
                if (!file_exists($file_paths)) {
                    mkdir($file_paths, 0777, true);
                }
                $info = $file->move($file_paths);
                if ($info) {
                    # 3 保存原始图片文件
                    $img_path = 'uploads/' . $file_path . '/' . $info->getSaveName();
                    $thumb_image = Image::open($img_path);
                    $date_path = 'uploads/' . $file_path . '/thumb/' . date('Ymd');
                    if (!file_exists($date_path)) {
                        mkdir($date_path, 0777, true);
                    }
                    # 4 保存缩略图
                    $thumb_path = $date_path . '/140_' . $info->getFilename();
                    $thumb_image->thumb(140, 140)->save($thumb_path);

                    $data['img'] = config('app_host') . $img_path;
                    $data['thumb_img'] = config('app_host') . $thumb_path;
                    # 5 成功结果返回
                    $ret_data = [
                        'code' => 1,
                        'msg' => 'SUCCESS',
                        'data' => $data
                    ];
                    return $ret_data;
                } else {
                    # 6 失败结果返回
                    $ret_data = [
                        'code' => 0,
                        'msg' => $file->getError(),
                        'data' => []
                    ];
                    return $ret_data;
                }
            }
        } catch (Exception $e) {
            $ret_data = [
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => []
            ];
            return $ret_data;
        }
    }

    /**
     * 图片上传
     * @param $name
     * @param $file_path
     * @param $width
     * @param $height
     * @return mixed
     */
    public function uploadImg($name, $file_path, $width, $height)
    {
        # 1 根据表单名称获取上传的图片文件
        $file = request()->file($name);
        if ($file) {
            # 2 将其保存在uploads文件夹下 | 后续如果想要保存在云端也可在此修改
            $file_paths = UPLOAD_PATH . $file_path;
            if (!file_exists($file_paths)) {
                mkdir($file_paths, 0777, true);
            }
            $info = $file->move($file_paths);
            if ($info) {
                # 3 保存原始图片文件
                $img_path = 'uploads/' . $file_path . '/' . $info->getSaveName();
                $image = Image::open($img_path);
                $date_path = 'uploads/' . $file_path . '/thumb/' . date('Ymd');
                if (!file_exists($date_path)) {
                    mkdir($date_path, 0777, true);
                }
                # 4 保存缩略图
                $thumb_path = $date_path . '/' . $info->getFilename();
                $image->thumb($width, $height)->save($thumb_path);
                $data['img'] = config('app_host') . $img_path;
                $data['thumb_img'] = config('app_host') . $thumb_path;
                # 5 成功结果返回
                $ret_data = [
                    'code' => 1,
                    'msg' => 'SUCCESS',
                    'data' => $data
                ];
                return $ret_data;
            } else {
                # 6 失败结果返回
                $ret_data = [
                    'code' => 0,
                    'msg' => $file->getError(),
                    'data' => []
                ];
                return $ret_data;
            }
        }
    }

    /**
     * kindEditor 富文本文件上传函数
     */
    public function uploadKindEditorImg()
    {
        # 1 判断七牛云是否开启
        $qn_config = config('qiniu.');
        if ($qn_config['is_open']) {
            # 2 将文件传输到七牛云
            $file = $_FILES['imgFile'];
            $qn_ret = $this->qiNiuUpload($file, $qn_config);
            if ($qn_ret['code']) {
                $ret = array(
                    'error' => 0,
                    'url' => $qn_ret['url'],
                );
            } else {
                $ret = array(
                    'error' => 1,
                    'url' => $qn_ret['msg'],
                );
            }
            exit(json_encode($ret));
        } else {
            # 3 根据表单名称获取上传的图片文件 | 保存到本地服务器
            # 可根据文件\public\static\js\kindeditor\php demo文件进行各种文件上传限制判断
            $file_path = "kindeditor";
            $file = request()->file("imgFile");
            if ($file) {
                # 4 进行上传文件
                $local_ret = $this->localUpload($file, $file_path);
                if ($local_ret['code']) {
                    $ret = array(
                        'error' => 0,
                        'url' => $local_ret['url'],
                    );
                } else {
                    $ret = array(
                        'error' => 1,
                        'url' => $local_ret['msg'],
                    );
                }
                exit(json_encode($ret));
            } else {
                # 6 失败结果返回
                $ret = array(
                    'error' => 1,
                    'message' => '图片上传失败',
                );
                exit(json_encode($ret));
            }
        }
    }

    /**
     * 上传文件到本地
     * @param $file
     * @param $file_path
     * @return array
     */
    protected function localUpload($file, $file_path)
    {
        $ret = array(
            'code' => 0,
            'msg' => 'suc',
            'url' => ''
        );

        # 1 判断是否已经上传过
        $file_info = $file->getInfo();
        $path_info = pathinfo($file_info['name']);
        # 1.1 通过pathinfo函数获取图片后缀名
        $ext = $path_info['extension'];
        # 1.2 判断文件是否上传过
        $con['admin_id'] = $this->yun_administrator['admin_uid'];
        $con['name'] = $file_info['name'];
        $con['md5'] = md5_file($file_info['tmp_name']);
        $con['sha1'] = sha1_file($file_info['tmp_name']);
        $con['size'] = $file_info['size'];
        $con['ext'] = $ext;
        $db_ret = Db::name('admin_upload')->where($con)->find();
        if (!empty($db_ret)) {
            $ret['code'] = 1;
            $ret['url'] = $db_ret['url'];
            return $ret;
        }

        # 2 将其保存在uploads文件夹下
        $file_paths = UPLOAD_PATH . $file_path;
        if (!file_exists($file_paths)) {
            mkdir($file_paths, 0777, true);
        }
        $info = $file->move($file_paths);

        # 3 判断返回结果
        if ($info) {
            $img_path = 'uploads/' . $file_path . '/' . $info->getSaveName();
            $img_url = config('app_host') . $img_path;
            $ret['url'] = $con['path'] = $con['url'] = $img_url;
            $ret['code'] = 1;
            Db::name('admin_upload')->insert($con);
        } else {
            $ret['msg'] = '文件上传失败';
        }
        return $ret;
    }

    /**
     * 上传文件到七牛云
     * @param $file
     * @param $conf
     * @return array
     * @throws \Exception
     */
    protected function qiNiuUpload($file, $conf)
    {
        # 1 定义返回值
        $ret = array(
            'code' => 0,
            'msg' => 'suc',
            'url' => ''
        );

        # 2 判断文件是否合法
        if (empty($file['tmp_name'])) {
            $ret['msg'] = '图片不合法';
            return $ret;
        }

        # 3 获取要上传文件的临时文件 | 扩展名
        $tmp_file = $file['tmp_name'];
        $path_info = pathinfo($file['name']);
        # 3.1 通过pathinfo函数获取图片后缀名
        $ext = $path_info['extension'];
        # 3.2 判断文件是否上传过
        $con['admin_id'] = $this->yun_administrator['admin_uid'];
        $con['name'] = $file['name'];
        $con['md5'] = md5_file($file['tmp_name']);
        $con['sha1'] = sha1_file($file['tmp_name']);
        $con['size'] = $file['size'];
        $con['ext'] = $ext;
        $db_ret = Db::name('admin_upload')->where($con)->find();
        if (!empty($db_ret)) {
            $ret['code'] = 1;
            $ret['url'] = $db_ret['url'];
            return $ret;
        }

        # 4 构建七牛云鉴权对象
        $auth = new Auth($conf['access_key'], $conf['secret_key']);
        # 4.1 生成上传需要的token
        $token = $auth->uploadToken($conf['bucket']);
        # 4.2 上传到七牛后保存的文件名
        $save_file_name = date('Y') . '/' . date('m') . '/' . substr(md5($tmp_file), 8, 5) . date('Ymd') . rand(0, 9999) . '.' . $ext;

        # 5 初始化UploadManager类
        $uploadMgr = new UploadManager();
        list($res, $err) = $uploadMgr->putFile($token, $save_file_name, $tmp_file);

        # 6 返回结果
        if ($err !== null) {
            $ret['msg'] = '图片上传失败！';
        } else {
            $ret['code'] = 1;
            # 6.1 写入上传记录
            $ret['url'] = $con['path'] = $con['url'] = $conf['domain'] . $save_file_name;
            Db::name('admin_upload')->insert($con);
        }
        return $ret;
    }
}